<template>
    <div style="display: flex; justify-content: space-evenly;">
        <div>
            <el-steps style="width: 500px;margin: 20px;" :active="active" finish-status="success">
                <el-step title="提交" />
                <el-step title="审核" />
                <el-step title="完成" />
            </el-steps>
            <el-form v-if="active == 0" class="form" ref="formRef" :model="formData" :rules="formRules">
                <el-form-item prop="staffNo" label-width="80px" label="工号">
                    <el-input v-model="formData.staffNo" disabled />
                </el-form-item>
                <el-form-item prop="staffName" label-width="80px" label="姓名">
                    <el-input v-model="formData.staffName" disabled />
                </el-form-item>
                <el-form-item prop="time" label-width="80px" label="加班日期">
                    <el-date-picker style="width: 100%;" v-model="formData.time" />
                </el-form-item>
                <el-form-item prop="duration" label-width="80px" label="加班时长">
                    <el-input type="number" v-model="formData.duration" />
                </el-form-item>
                <el-form-item prop="reason" label-width="80px" label="备注">
                    <el-input v-model="formData.reason" type="textarea" />
                </el-form-item>
                <el-form-item class="btn">
                    <el-button type="primary" @click="onSubmit">提交</el-button>
                    <el-button type="primary" @click="onReset">重置</el-button>
                </el-form-item>
            </el-form>
            <div class="steps-box" v-else-if="active == 1">
                <div class="steps-status">
                    <el-icon v-loading="true" size="40" />
                    <div style="margin-top: 20px;">审核中，请耐心等待</div>
                </div>
                <div>
                    <el-button type="primary" @click="newDel">撤销请假</el-button>
                    <el-button type="primary" @click="newAdd">新增请假</el-button>
                </div>
            </div>
            <div class="steps-box" v-else>
                <div class="steps-status">
                    <el-icon size="40" color="#67c23a"><Select /></el-icon>
                    <div style="margin-top: 20px;">审核完成，{{ messageTip }}</div>
                </div>
                <el-button style="width: 85px;" type="primary" @click="newAdd">新增请假</el-button>
            </div>
        </div>
        <div class="scrollbar">
            <h4>历史加班列表</h4>
            <el-table style="width: 350px;" max-height="300" :data="tableList" show-overflow-tooltip
                @row-click="handleOpen">
                <el-table-column prop="time" label="加班日期" :formatter="toDate" />
                <el-table-column prop="duration" label="加班时长" />
                <el-table-column prop="audit" label="审核状态" :formatter="toAudit" />
            </el-table>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue';
import { useUserStore } from '@/store/user';
import { addOvertime, queryOvertime, deleteOvertime } from '@/api/employee';
import { timeProcessing } from '@/utils/date';
import dayjs from 'dayjs';

const userStore = useUserStore();
const info = computed(() => userStore.userInfo);

const active = ref(0);

const tableList = ref([]);

const formRef = ref(null)
const formData = reactive({
    staffNo: info.value.staff_no,
    staffName: info.value.staff_name
})

const messageTip = ref('');
const selectRowId = ref();

const formRules = reactive({
    staffNo: [
        { required: true, message: '工号不能为空', trigger: 'blur' }
    ],
    staffName: [
        { required: true, message: '姓名不能为空', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择请假类型', trigger: 'blur' }
    ],
    time: [
        { required: true, message: '请选择请假时间', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (!value) return callback();

                const selectedDate = dayjs(value);
                const today = dayjs().startOf('day');

                if (selectedDate.isBefore(today)) {
                    callback(new Error('请假时间不能早于今天'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    duration: [
        { required: true, message: '请输入请假天数', trigger: 'blur' },
        {
            pattern: /^(0|[1-9]\d*)(\.\d+)?$/,
            message: '请输入有效的天数',
            trigger: 'blur'
        },
        {
            validator: (rule, value, callback) => {
                if (value <= 0) {
                    callback(new Error('请假天数必须大于0'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    reason: [
        { required: true, message: '请输入请假原因', trigger: 'blur' }
    ]
});

const onSubmit = () => {
    ElMessageBox.confirm('确认提交申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            let data = {
                ...formData,
                time: timeProcessing(formData.time, 'date'),
                departmentName: info.value.department_name,
                position: info.value.position,
            }
            const res = await addOvertime(data);
            if (res.code == 0) {
                active.value = 1;
                ElMessage.success('提交成功！');
                queryCard();
            } else {
                ElMessage.error('提交失败！');
            }
        } catch {
            console.log("请求失败");
        }
    }).catch(() => {
        console.log('取消');
    })
}

const queryCard = async () => {
    try {
        const data = {
            staffNo: info.value.staff_no,
            staffName: info.value.staff_name
        }
        const res = await queryOvertime(data);
        tableList.value = res.data.list;
    } catch {
        console.log("请求失败");
    }
}

const toDate = (row, value, cellValue) => {
    return timeProcessing(cellValue, 'date');
}

const toAudit = (row, value, cellValue) => {
    let str = '';
    if (cellValue == 0) str = '未审核';
    if (cellValue == 1) str = '驳回';
    if (cellValue == 2) str = '通过';
    return str;
}

const onReset = () => {
    formData.staffNo = info.value.staff_no;
    formData.staffName = info.value.staff_name;
    formData.time = '';
    formData.duration = '';
    formData.reason = '';
}

const handleOpen = (row) => {
    selectRowId.value = row.id;
    if (row.audit == 0) {
        active.value = 1;
    } else {
        active.value = 3;
        if (row.audit == 1) messageTip.value = '该加班申请未通过';
        if (row.audit == 2) messageTip.value = '加班申请通过';
    }
}

const newAdd = () => {
    active.value = 0;
    onReset();
}

const newDel = () => {
    const data = {
        ids: [selectRowId.value]
    };
    ElMessageBox.confirm('确认撤销该条加班申请吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await deleteOvertime(data);
            if (res.code === 0) {
                ElMessage.success('删除成功！');
                queryCard();
                newAdd();
            } else {
                ElMessage.error('删除失败！');
            }
        } catch {
            console.log("请求失败");
        }
    }).catch(() => {
        console.log('取消删除');
    })
}

watch(active, (newVal, oldVal) => {
    if (newVal > 3) active.value = 0;
})

onMounted(() => {
    if (Object.keys(info.value).length > 0) {
        formData.staffNo = info.value.staff_no;
        formData.staffName = info.value.staff_name;
        formData.remarks = '';
    } else {
        let userInfo = JSON.parse(sessionStorage.getItem('userInfo'));
        formData.staffNo = userInfo.staff_no;
        formData.staffName = userInfo.staff_name;
        info.value.staff_no = userInfo.staff_no;
        info.value.staff_name = userInfo.staff_name;
    }
    queryCard();
})

</script>

<style lang="scss" scoped>
.form {
    width: 500px;
    margin: 20px;
}

.btn {
    :deep(.el-form-item__content) {
        justify-content: center !important;
    }
}

.scrollbar {
    box-sizing: border-box;
    padding-left: 100px;
}

.scrollbar-demo-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 40px;
    margin: 10px;
    text-align: center;
    border-radius: 4px;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
}

.steps-box {
    display: flex;
    flex-direction: column;
    align-items: center;

    .steps-status {
        width: 100%;
        height: 240px;
        box-sizing: border-box;
        padding-top: 30px;
        display: flex;
        flex-direction: column;
        align-items: center;
    }
}
</style>